// 获取请求地址
var apiList = {
    // base: 'http://lishui:8200/mobile/'
    base: 'http://valentine.12yishu.com/mobile/'
};

var city = "auto";
//119.02828,31.651133
var lng = Number(119.02828);
var lat = Number(31.651133);
var centerPoint = [lng,lat];

// 应用版本
var version = "1.0.0";
//页面展示条数
var rows = 20;
var userInfo = null;

// 判断页面是微信登陆
function isWechatLogin() {
    //userAgent 属性是一个只读的字符串，声明了浏览器用于 HTTP 请求的用户代理头的值。
    var ua = window.navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) === 'micromessenger';
}

// 获取本地存储用户信息
function getLocalUserInfo() {
    if(userInfo) {
        console.log('userInfo: ', user);
        return userInfo;
    }
    var user = localStorage.getItem('user_info');

    console.log('UserRawData: ', user);
    if(!user || user == 'undefined') return null;
    user = JSON.parse(user);
    console.log('localUser: ', user);
    if(!user || !user.id) {
        return null;
    } else {
        return user;
    }
}
// 设置本地存储用户信息
function setLocalUserInfo(info) {
    userInfo = info;
    localStorage.setItem('user_info', JSON.stringify(info || {}));
}

// 初始化用户信息
if(localStorage.getItem('user_info')) {
    userInfo = getLocalUserInfo();
}

// 设置网络请求token
function setRequestToken(token) {
    return localStorage.setItem('request_token', token);
}
function getRequestToken() {
    return localStorage.getItem('request_token');
}

// 设置 Score
function setScore(score) {
    return localStorage.setItem('qixi_score', score);
}
function getScore() {
    var score = localStorage.getItem('qixi_score');
    return score || '**';
}

var baseApi = {};
mui.each(['get', 'post'], function(index, method) {
    baseApi[method] = function(api, data, callback, errorCallBack) {
        if(typeof data === 'function') {
            callback = data;
            data = {};
        }
        if(typeof callback === 'undefined') {
            callback = function() {}
        }
        if(typeof errorCallBack === 'undefined') {
            errorCallBack = function () {}
        }

        var url = http_build_query({
            token: getRequestToken(),
            _random: Math.random()
        }, getRequestAddressUrl('base') + api);

        data.referer = location.pathname;

        var params = {
            url: url,
            type: method.toUpperCase(),
            data: data,
            dataType: 'json',
            beforeSend: function () {
                // alert(11111);
            },
            error: function (res) {
                // alert(JSON.stringify(res));
            },
            success: function(result) {
                // alert(JSON.stringify(result));
                if(result.token) {
                    // 重置token
                    setRequestToken(result.token);
                }
                console.log(result);
                if(result.status == 0) {
                    if(errorCallBack) {
                        errorCallBack();
                    }
                    mui.toast(result.result);
                } else if(result.status == 1000) {
                    // 弹窗提示
                    mui.alert(result.result, '温馨提示', '确定', errorCallBack(result));
                } else if(result.status == 302) {
                    if(/user\/info/.test(url)) {
                        setLocalUserInfo(null);
                    }
                    location.href = result.url;
                } else {
                    console.log(JSON.stringify(result));
                    return callback(result.result || result.msg);
                }
            }
        }
        return $.ajax(params);
    };
});

// 页面跳转
$('body').on('tap', '.open-url', function() {
    var url = $(this).is('a') ? $(this).attr('href') : $(this).data('url');
    var data = $(this).data();
    data = data || {};
    delete data.url;
    delete data.href;

    // 缓存
    data._random = Math.random();

    if(typeof plus != 'undefined') {
        data.prevWebviewId = plus.webview.currentWebview().id;
        pageChange({
            pageUrl: url,
            createNew: false,
            postData: data
        });
    } else {
        location.href = http_build_query(data, url);
    }

    return false;
});

// 分享
baseApi.get(
    'wechat/jssdkconfig',
    {url: location.href},
    function (result){
        console.log(result);
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: result.appId, // 必填，公众号的唯一标识
            timestamp: result.timestamp, // 必填，生成签名的时间戳
            nonceStr: result.nonceStr, // 必填，生成签名的随机串
            signature: result.signature,// 必填，签名
            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone'] // 必填，需要使用的JS接口列表
        });

    }
);

var shareConfig = {
    title: '熬七夕不如玩游戏', // 分享标题
    desc: '我在艺来二趣七夕活动中帮牛郎坚持了**秒，差一点就拿到了第一，快来挑战排行榜！', // 分享描述
    link: 'http://valentine.12yishu.com/wap', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
    imgUrl: 'http://valentine.12yishu.com/wap/images/share_ico.jpg', // 分享图标
    type: '', // 分享类型,music、video或link，不填默认为link
    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
    success: function () {
        // 用户点击了分享后执行的回调函数
        mui.toast('分享成功');
    },
    cancel: function () {
        // 用户取消分享后执行的回调函数
        mui.toast('取消了分享');
    }
};
wx.ready(function(){
    // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
    // 分享到朋友圈
    wx.onMenuShareTimeline(shareConfig);
    // 分享给好友
    wx.onMenuShareAppMessage(shareConfig);
    // 分享到QQ
    wx.onMenuShareQQ(shareConfig);
    // 分享到QQ空间
    wx.onMenuShareQZone(shareConfig);
});

// 图片的请求地址
//var filesHost = getRequestAddressUrl("filesHost");
var loginid = window.localStorage.getItem("uid");
//var loginid = "1000171372";

// 检查登陆状态
function checkUserLogin() {
    console.log(JSON.stringify(userInfo));
    if(1 || !userInfo && /(login|register)\.html/.test(location.href) === false) {
        // 微信注册/登录
        baseApi.get(
            'user/info',
            function (result){
                setLocalUserInfo(result);
                if(result.subscribe == 0) {

                    mui.alert('<img width="100%" src="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGX8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyNTN0WHBmQzRld2sxMDAwMDAwN2MAAgTWOnRbAwQAAAAA" />', '请长按二维码关注公众号后开始游戏', '确定', function () {location.reload()});
                }
            }
        );
    }
}

// 微信授权返回
var code = getQueryString('code');
if(code) {
    // 微信注册/登录
    baseApi.get(
        'user/info',
        {code: code},
        function (result){
            setLocalUserInfo(result);
            location.href = http_build_query({random: Math.random()}, location.pathname);
        }
    );
} else {
    checkUserLogin();
}

// 获取请求参数
// name：参数名称
function getQueryString(name) {
    if( typeof plus != 'undefined') {
        var self = plus.webview.currentWebview();
        var value = self[name];
        if(isEmpty(value)) {
            value = ""
        }
        return decodeURIComponent(value);
    } else {
        if(name) {
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r!=null) return decodeURIComponent(r[2]); return '';
        } else {
            var params = window.location.search.substr(1).split('&');
            var query = {};
            for(var i = 0; i < params.length; i++) {
                if(params[i]) {
                    var arr = params[i].split('=');
                    query[arr[0]] = decodeURIComponent(arr[1]);
                }
            }
            return query;
        }
    }
}
//生成32位随机码
function newGuid() {
    var guid = "";
    for(var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
    }
    return guid;
};
// 获取请求地址
function getRequestAddressUrl(key) {
    return apiList[key];
}

function http_build_query (formdata, url) { // eslint-disable-line camelcase
    //  discuss at: http://locutus.io/php/http_build_query/
    // original by: Kevin van Zonneveld (http://kvz.io)
    // improved by: Legaev Andrey
    // improved by: Michael White (http://getsprink.com)
    // improved by: Kevin van Zonneveld (http://kvz.io)
    // improved by: Brett Zamir (http://brett-zamir.me)
    //  revised by: stag019
    //    input by: Dreamer
    // bugfixed by: Brett Zamir (http://brett-zamir.me)
    // bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
    //      note 1: If the value is null, key and value are skipped in the
    //      note 1: http_build_query of PHP while in locutus they are not.
    //   example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;')
    //   returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk'
    //   example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_')
    //   returns 2: 'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&php=hypertext+processor&cow=milk'

    var value, key, tmp = [], argSeparator = '&';

    var _httpBuildQueryHelper = function (key, val, argSeparator) {
        var k, tmp = [];
        if (val === true) {
            val = '1';
        } else if (val === false) {
            val = '0';
        }
        if (val !== null) {
            if (typeof val === 'object') {
                for (k in val) {
                    if (val[k] !== null) {
                        tmp.push(_httpBuildQueryHelper(key + '[' + k + ']', val[k], argSeparator));
                    }
                }
                return tmp.join(argSeparator);
            } else if (typeof val !== 'function') {
                return encodeURIComponent(key) + '=' + encodeURIComponent(val);
            } else {
                throw new Error('There was an error processing for http_build_query().');
            }
        } else {
            return '';
        }
    };

    if (!argSeparator) {
        argSeparator = '&';
    }
    for (key in formdata) {
        value = formdata[key];
        var query = _httpBuildQueryHelper(key, value, argSeparator);
        if (query !== '') {
            tmp.push(query);
        }
    }

    url && (url = url.replace(/[&?]+$/, ''));
    var paramString = tmp.join(argSeparator);
    var result = !url ? '' : url + (!paramString ? '' : (url.indexOf('?') != -1 ? '&' : '?'));
    result += paramString;
    return result;
}

// 四舍五入
Number.prototype.round = function (n) {
    var digit = Math.pow(10, n);
    return Math.round(this*digit)/digit;
}
// 进位取整
Number.prototype.ceil = function (n) {
    var digit = Math.pow(10, n);
    return Math.ceil(this*digit)/digit;
}
// 退位取整
Number.prototype.floor = function (n) {
    var digit = Math.pow(10, n);
    return Math.floor(this*digit)/digit;
}
// 去除前后空格
String.prototype.trim = function() {
    return this.replace( /(^\s*)|(\s*$)/g, '');
}
// 字符串转化为整型
String.prototype.toInt = function() {
    var num = parseInt(this);
    return isNaN(num) ? 0 : num;
}
// 字符串转化为浮点型
String.prototype.toFloat = function() {
    var num = parseFloat(this);
    return isNaN(num) ? 0 : num;
}
// 字符串截取替换
String.prototype.strCut = function(len, replaceWith) {
    var string = this;
    return string.length > len ? string.substr(0, len - 3) + (replaceWith || '...') : string;
}
// 首字母大写
String.prototype.ucFirst = function() {
    var string = this;
    return string[0].toUpperCase() + string.substr(1);
}
// 替换全部（ 仿 php preg_replace ）
String.prototype.replaceAll = function(from, to) {
    var string = this;
    for(var i in from) {
        var regexp = new RegExp(from[i], 'g');
        string = string.replace(regexp, to[i]);
    }
    return string;
}

// 字符格式化
String.prototype.number_format = Number.prototype.number_format = function (decimals, decPoint, thousandsSep) {
    var number = this;
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
    var n = !isFinite(+number) ? 0 : +number
    var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
    var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
    var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
    var s = ''

    var toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec)
        return '' + (Math.round(n * k) / k)
                .toFixed(prec)
    }

    // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || ''
        s[1] += new Array(prec - s[1].length + 1).join('0')
    }

    return s.join(dec);
};

// 文件 等 大小格式化
String.prototype.size_format = Number.prototype.size_format = function (digit) {
    digit = digit || 2;
    var G = 1024*1024*1024;
    var M = 1024*1024;
    var K = 1024;

    if(this >= G) {
        var val = this / G;
        return val.number_format(2) + 'G';
    }
    if(this >= M) {
        var val = this / M;
        return val.number_format(2) + 'M';
    }
    if(this >= K) {
        var val = this / K;
        return val.number_format(2) + 'K';
    }

    return val.number_format(2) + 'byte';
};
